﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YYSite.Common
{
  public  class SqlDynamicParameters: DynamicParameters
    {
        public  void Add(string name, object value, DbType? dbType, int? size)
        {
            base.Add(name, GetSqlValue(value), dbType, ParameterDirection.Input, size);
        }
        public new void Add(string name, object value, DbType? dbType, ParameterDirection? direction, int? size)
        {
            base.Add(name, GetSqlValue(value), dbType, direction, size);
        }

        public new void Add(string name, object value = null, DbType? dbType = default(DbType?), ParameterDirection? direction = default(ParameterDirection?), int? size = default(int?), byte? precision = default(byte?), byte? scale = default(byte?))
        {
            base.Add(name, GetSqlValue(value), dbType, direction, size, precision, scale);
        }


        /// <summary>
        /// 处理特殊情况
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        protected object GetSqlValue(object value)
        {
            if (value == null)
            {
                return DBNull.Value;
            }
            else if (Convert.IsDBNull(value))
            {
                return DBNull.Value;
            }
            else if (value is Guid && Guid.Parse(value.ToString()) == Guid.Empty)
            {
                return DBNull.Value;
            }
            else if (value is DateTime && Convert.ToDateTime(value) == DateTime.MinValue)
            {
                return DBNull.Value;
            }
            else
            {
                return value;
            }

        }
    }
}
